<template>
  <div class="goods-detail-view">
    <!-- 加载状态 -->
    <div v-if="goodsStore.isLoading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 商品详情 -->
    <div v-else-if="goods" class="goods-detail">
      <!-- 商品图片和基本信息 -->
      <div class="goods-main">
        <!-- 图片展示 -->
        <div class="image-section">
          <el-carousel 
            v-if="goods.images && goods.images.length > 0"
            height="400px" 
            :interval="0"
            arrow="hover"
            indicator-position="outside"
          >
            <el-carousel-item v-for="(image, index) in goods.images" :key="index">
              <el-image
                :src="image"
                :alt="`${goods.title} - 图片${index + 1}`"
                class="detail-image"
                fit="contain"
                :preview-src-list="goods.images"
                :initial-index="index"
              />
            </el-carousel-item>
          </el-carousel>
          
          <div v-else class="no-image">
            <el-icon class="no-image-icon"><Picture /></el-icon>
            <span>暂无图片</span>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="info-section">
          <div class="goods-header">
            <h1 class="goods-title">{{ goods.title }}</h1>
            <div class="goods-status">
              <el-tag 
                :type="getStatusType(goods.status)" 
                size="large"
                class="status-tag"
              >
                {{ goods.status }}
              </el-tag>
            </div>
          </div>

          <!-- 价格信息 -->
          <div class="price-section">
            <div class="current-price">¥{{ formatPrice(goods.price) }}</div>
            <div v-if="goods.originalPrice" class="original-price">
              原价 ¥{{ formatPrice(goods.originalPrice) }}
            </div>
          </div>

          <!-- 商品属性 -->
          <div class="attributes">
            <div class="attribute-item">
              <span class="label">分类：</span>
              <el-tag type="info">{{ goods.category }}</el-tag>
            </div>
            <div class="attribute-item">
              <span class="label">成色：</span>
              <el-tag type="success">{{ goods.condition }}</el-tag>
            </div>
            <div class="attribute-item">
              <span class="label">发布时间：</span>
              <span>{{ formatTime(goods.createdAt) }}</span>
            </div>
            <div class="attribute-item">
              <span class="label">浏览次数：</span>
              <span>{{ goods.viewCount || 0 }} 次</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button
              :icon="isCollected ? StarFilled : Star"
              :type="isCollected ? 'danger' : 'info'"
              @click="toggleCollect"
              :loading="collectLoading"
            >
              {{ isCollected ? '已收藏' : '收藏' }}
            </el-button>
            
            <el-button
              type="primary"
              :icon="ChatDotRound"
              size="large"
              @click="contactSeller"
              class="contact-btn"
            >
              联系卖家
            </el-button>
          </div>
        </div>
      </div>

      <!-- 商品描述 -->
      <div class="description-section">
        <h3>商品描述</h3>
        <div class="description-content">
          {{ goods.description }}
        </div>
      </div>

      <!-- 卖家信息 -->
      <div class="seller-section">
        <h3>卖家信息</h3>
        <div class="seller-card">
          <div class="seller-info">
            <el-avatar :src="goods.sellerInfo?.avatar" :size="60">
              {{ goods.sellerInfo?.username?.charAt(0) }}
            </el-avatar>
            <div class="seller-details">
              <h4>{{ goods.sellerInfo?.username }}</h4>
              <p>{{ goods.sellerInfo?.college }}</p>
              <div class="seller-stats">
                <span>加入时间：{{ formatTime(goods.sellerInfo?.createdAt) }}</span>
              </div>
            </div>
          </div>
          
          <div class="contact-info" v-if="showContactInfo">
            <el-alert
              title="联系方式"
              type="success"
              :closable="false"
            >
              <p>手机号：{{ goods.sellerInfo?.phone }}</p>
              <p>建议通过手机号联系卖家进行交易</p>
            </el-alert>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品不存在 -->
    <div v-else class="not-found">
      <el-empty description="商品不存在或已被删除">
        <el-button type="primary" @click="$router.push('/')">
          返回首页
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useGoodsStore } from '@/stores/goodsStore'
import { useUserStore } from '@/stores/userStore'
import { collectApi } from '@/api/collect'
import { formatPrice, formatTime } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import ImageUpload from '@/components/ImageUpload.vue'
import { 
  Picture, 
  Star, 
  StarFilled, 
  ChatDotRound 
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const goodsStore = useGoodsStore()
const userStore = useUserStore()

// 商品数据
const goods = computed(() => goodsStore.currentGoods)

// 收藏状态
const isCollected = ref(false)
const collectLoading = ref(false)

// 是否显示联系信息
const showContactInfo = ref(false)

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '在售': return 'success'
    case '已售': return 'info'
    case '下架': return 'warning'
    default: return 'info'
  }
}

// 检查收藏状态
const checkCollectStatus = async () => {
  if (userStore.isLoggedIn && goods.value) {
    try {
      const response = await collectApi.checkCollected(goods.value.goodsId)
      isCollected.value = response.data.isCollected
    } catch (error) {
      console.error('检查收藏状态失败:', error)
    }
  }
}

// 切换收藏状态
const toggleCollect = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  collectLoading.value = true
  try {
    if (isCollected.value) {
      await collectApi.removeCollect(goods.value.goodsId)
      isCollected.value = false
      ElMessage.success('已取消收藏')
    } else {
      await collectApi.addCollect(goods.value.goodsId)
      isCollected.value = true
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    collectLoading.value = false
  }
}

// 联系卖家
const contactSeller = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (goods.value.sellerId === userStore.userInfo?.userId) {
    ElMessage.warning('这是你自己发布的商品')
    return
  }

  try {
    await ElMessageBox.confirm(
      '点击确认后将显示卖家联系方式，请文明交易，注意安全。',
      '联系卖家',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    showContactInfo.value = true
  } catch {
    // 用户取消
  }
}

// 组件挂载时获取商品详情
onMounted(async () => {
  const goodsId = route.params.id
  if (goodsId) {
    await goodsStore.getGoodsDetail(goodsId)
    await checkCollectStatus()
  }
})
</script>

<style scoped>
.goods-detail-view {
  max-width: 1200px;
  margin: 0 auto;
}

.loading-container {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.goods-detail {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.goods-main {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.image-section {
  position: relative;
}

.detail-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.no-image {
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  color: #999;
}

.no-image-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.goods-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 15px;
}

.goods-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  flex: 1;
}

.status-tag {
  flex-shrink: 0;
}

.price-section {
  padding: 20px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.current-price {
  font-size: 32px;
  font-weight: 700;
  color: #e74c3c;
  margin-bottom: 8px;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.attributes {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attribute-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.contact-btn {
  flex: 1;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.description-section,
.seller-section {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.description-section h3,
.seller-section h3 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f0f0;
}

.description-content {
  font-size: 16px;
  line-height: 1.8;
  color: #555;
  white-space: pre-wrap;
}

.seller-card {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.seller-info {
  display: flex;
  gap: 15px;
  align-items: center;
}

.seller-details h4 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.seller-details p {
  color: #666;
  margin-bottom: 8px;
}

.seller-stats {
  font-size: 14px;
  color: #999;
}

.contact-info {
  margin-top: 15px;
}

.not-found {
  background: white;
  padding: 60px 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .goods-main {
    grid-template-columns: 1fr;
    gap: 20px;
    padding: 20px;
  }
  
  .image-section {
    order: 1;
  }
  
  .info-section {
    order: 2;
  }
  
  .goods-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .goods-title {
    font-size: 20px;
  }
  
  .current-price {
    font-size: 28px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .description-section,
  .seller-section {
    padding: 20px;
  }
  
  .seller-info {
    flex-direction: column;
    text-align: center;
  }
}
</style>